{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "import sys\n",
    "sys.path.append('/data/users/fyx/NTMC-Community/MatchZoo-py/')\n",
    "import matchzoo as mz"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2019-03-20T09:35:56.628130Z",
     "start_time": "2019-03-20T09:35:45.661384Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "matchzoo version 1.0\n",
      "`ranking_task` initialized with metrics [normalized_discounted_cumulative_gain@3(0.0), normalized_discounted_cumulative_gain@5(0.0), mean_average_precision(0.0)]\n",
      "data loading ...\n",
      "data loaded as `train_pack_raw` `dev_pack_raw` `test_pack_raw`\n"
     ]
    }
   ],
   "source": [
    "%run init.ipynb"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2019-03-20T09:35:56.633000Z",
     "start_time": "2019-03-20T09:35:56.630450Z"
    }
   },
   "outputs": [],
   "source": [
    "preprocessor = mz.models.DUET.get_default_preprocessor(\n",
    "    filter_mode='df',\n",
    "    filter_low_freq=2,\n",
    "    truncated_mode='post',\n",
    "    truncated_length_left=10,\n",
    "    truncated_length_right=40,\n",
    "    ngram_size=3\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2019-03-20T09:36:06.249211Z",
     "start_time": "2019-03-20T09:35:56.634788Z"
    }
   },
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "Processing text_left with chain_transform of Tokenize => Lowercase => PuncRemoval: 100%|██████████| 2118/2118 [00:00<00:00, 6447.42it/s]\n",
      "Processing text_right with chain_transform of Tokenize => Lowercase => PuncRemoval: 100%|██████████| 18841/18841 [00:05<00:00, 3617.47it/s]\n",
      "Processing text_right with append: 100%|██████████| 18841/18841 [00:00<00:00, 803890.84it/s]\n",
      "Building FrequencyFilter from a datapack.: 100%|██████████| 18841/18841 [00:00<00:00, 108708.35it/s]\n",
      "Processing text_right with transform: 100%|██████████| 18841/18841 [00:00<00:00, 128194.12it/s]\n",
      "Processing text_left with extend: 100%|██████████| 2118/2118 [00:00<00:00, 488858.46it/s]\n",
      "Processing text_right with extend: 100%|██████████| 18841/18841 [00:00<00:00, 671215.47it/s]\n",
      "Building Vocabulary from a datapack.: 100%|██████████| 404432/404432 [00:00<00:00, 2495672.00it/s]\n",
      "Processing text_left with transform: 100%|██████████| 2118/2118 [00:00<00:00, 46972.02it/s]\n",
      "Processing text_right with transform: 100%|██████████| 18841/18841 [00:01<00:00, 12598.66it/s]\n",
      "Processing text_left with extend: 100%|██████████| 2118/2118 [00:00<00:00, 516785.10it/s]\n",
      "Processing text_right with extend: 100%|██████████| 18841/18841 [00:00<00:00, 385718.66it/s]\n",
      "Building Vocabulary from a datapack.: 100%|██████████| 1976372/1976372 [00:00<00:00, 2799741.35it/s]\n",
      "Processing text_left with chain_transform of Tokenize => Lowercase => PuncRemoval: 100%|██████████| 2118/2118 [00:00<00:00, 7512.74it/s]\n",
      "Processing text_right with chain_transform of Tokenize => Lowercase => PuncRemoval: 100%|██████████| 18841/18841 [00:05<00:00, 3447.10it/s]\n",
      "Processing text_right with transform: 100%|██████████| 18841/18841 [00:00<00:00, 112829.34it/s]\n",
      "Processing text_left with transform: 100%|██████████| 2118/2118 [00:00<00:00, 176621.59it/s]\n",
      "Processing text_right with transform: 100%|██████████| 18841/18841 [00:00<00:00, 103267.97it/s]\n",
      "Processing text_left with transform: 100%|██████████| 2118/2118 [00:00<00:00, 596250.48it/s]\n",
      "Processing text_right with transform: 100%|██████████| 18841/18841 [00:00<00:00, 606270.09it/s]\n",
      "Processing length_left with len: 100%|██████████| 2118/2118 [00:00<00:00, 639103.30it/s]\n",
      "Processing length_right with len: 100%|██████████| 18841/18841 [00:00<00:00, 688621.98it/s]\n",
      "Processing text_left with chain_transform of Tokenize => Lowercase => PuncRemoval: 100%|██████████| 122/122 [00:00<00:00, 7693.66it/s]\n",
      "Processing text_right with chain_transform of Tokenize => Lowercase => PuncRemoval: 100%|██████████| 1115/1115 [00:00<00:00, 4043.63it/s]\n",
      "Processing text_right with transform: 100%|██████████| 1115/1115 [00:00<00:00, 102079.04it/s]\n",
      "Processing text_left with transform: 100%|██████████| 122/122 [00:00<00:00, 96877.15it/s]\n",
      "Processing text_right with transform: 100%|██████████| 1115/1115 [00:00<00:00, 110836.82it/s]\n",
      "Processing text_left with transform: 100%|██████████| 122/122 [00:00<00:00, 171943.91it/s]\n",
      "Processing text_right with transform: 100%|██████████| 1115/1115 [00:00<00:00, 520495.15it/s]\n",
      "Processing length_left with len: 100%|██████████| 122/122 [00:00<00:00, 185736.87it/s]\n",
      "Processing length_right with len: 100%|██████████| 1115/1115 [00:00<00:00, 583559.89it/s]\n",
      "Processing text_left with chain_transform of Tokenize => Lowercase => PuncRemoval: 100%|██████████| 237/237 [00:00<00:00, 7144.09it/s]\n",
      "Processing text_right with chain_transform of Tokenize => Lowercase => PuncRemoval: 100%|██████████| 2300/2300 [00:00<00:00, 4000.44it/s]\n",
      "Processing text_right with transform: 100%|██████████| 2300/2300 [00:00<00:00, 96957.66it/s]\n",
      "Processing text_left with transform: 100%|██████████| 237/237 [00:00<00:00, 145904.89it/s]\n",
      "Processing text_right with transform: 100%|██████████| 2300/2300 [00:00<00:00, 119835.77it/s]\n",
      "Processing text_left with transform: 100%|██████████| 237/237 [00:00<00:00, 275895.10it/s]\n",
      "Processing text_right with transform: 100%|██████████| 2300/2300 [00:00<00:00, 597331.22it/s]\n",
      "Processing length_left with len: 100%|██████████| 237/237 [00:00<00:00, 264023.92it/s]\n",
      "Processing length_right with len: 100%|██████████| 2300/2300 [00:00<00:00, 680173.39it/s]\n"
     ]
    }
   ],
   "source": [
    "train_pack_processed = preprocessor.fit_transform(train_pack_raw)\n",
    "dev_pack_processed = preprocessor.transform(dev_pack_raw)\n",
    "test_pack_processed = preprocessor.transform(test_pack_raw)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2019-03-20T09:36:06.262937Z",
     "start_time": "2019-03-20T09:36:06.253350Z"
    }
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'ngram_process_unit': <matchzoo.preprocessors.units.ngram_letter.NgramLetter at 0x7fbf130aa908>,\n",
       " 'filter_unit': <matchzoo.preprocessors.units.frequency_filter.FrequencyFilter at 0x7fbf130aaac8>,\n",
       " 'vocab_unit': <matchzoo.preprocessors.units.vocabulary.Vocabulary at 0x7fc01b431c88>,\n",
       " 'vocab_size': 16675,\n",
       " 'embedding_input_dim': 16675,\n",
       " 'ngram_vocab_unit': <matchzoo.preprocessors.units.vocabulary.Vocabulary at 0x7fbf1036f5c0>,\n",
       " 'ngram_vocab_size': 6602}"
      ]
     },
     "execution_count": 5,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "preprocessor.context"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [],
   "source": [
    "triletter_callback = mz.dataloader.callbacks.Ngram(preprocessor, mode='sum')\n",
    "trainset = mz.dataloader.Dataset(\n",
    "    data_pack=train_pack_processed,\n",
    "    mode='pair',\n",
    "    num_dup=2,\n",
    "    num_neg=1,\n",
    "    callbacks=[triletter_callback]\n",
    ")\n",
    "testset = mz.dataloader.Dataset(\n",
    "    data_pack=test_pack_processed,\n",
    "    callbacks=[triletter_callback]\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [],
   "source": [
    "padding_callback = mz.models.DUET.get_default_padding_callback(\n",
    "    fixed_length_left=10,\n",
    "    fixed_length_right=40,\n",
    "    pad_word_value=0,\n",
    "    pad_word_mode='pre',\n",
    "    with_ngram=True\n",
    ")\n",
    "\n",
    "trainloader = mz.dataloader.DataLoader(\n",
    "    dataset=trainset,\n",
    "    batch_size=20,\n",
    "    stage='train',\n",
    "    resample=True,\n",
    "    sort=False,\n",
    "    callback=padding_callback\n",
    ")\n",
    "testloader = mz.dataloader.DataLoader(\n",
    "    dataset=testset,\n",
    "    batch_size=20,\n",
    "    stage='dev',\n",
    "    callback=padding_callback\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2019-03-20T09:36:06.413530Z",
     "start_time": "2019-03-20T09:36:06.267256Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "DUET(\n",
      "  (lm_conv1d): Conv1d(40, 100, kernel_size=(1,), stride=(1,))\n",
      "  (lm_mlp): Sequential(\n",
      "    (0): Sequential(\n",
      "      (0): Linear(in_features=1000, out_features=100, bias=True)\n",
      "      (1): Tanh()\n",
      "    )\n",
      "    (1): Sequential(\n",
      "      (0): Linear(in_features=100, out_features=100, bias=True)\n",
      "      (1): Tanh()\n",
      "    )\n",
      "    (2): Sequential(\n",
      "      (0): Linear(in_features=100, out_features=100, bias=True)\n",
      "      (1): Tanh()\n",
      "    )\n",
      "  )\n",
      "  (lm_linear): Sequential(\n",
      "    (0): Linear(in_features=100, out_features=1, bias=True)\n",
      "    (1): ReLU()\n",
      "  )\n",
      "  (dm_conv_activation_func): ReLU()\n",
      "  (dm_conv_left): Conv1d(6602, 100, kernel_size=(3,), stride=(1,))\n",
      "  (dm_mlp_left): Sequential(\n",
      "    (0): Linear(in_features=100, out_features=100, bias=True)\n",
      "    (1): ReLU()\n",
      "  )\n",
      "  (dm_conv1_right): Conv1d(6602, 100, kernel_size=(3,), stride=(1,))\n",
      "  (dm_conv2_right): Conv1d(100, 100, kernel_size=(1,), stride=(1,))\n",
      "  (dm_mlp): Sequential(\n",
      "    (0): Sequential(\n",
      "      (0): Linear(in_features=900, out_features=100, bias=True)\n",
      "      (1): Tanh()\n",
      "    )\n",
      "    (1): Sequential(\n",
      "      (0): Linear(in_features=100, out_features=100, bias=True)\n",
      "      (1): Tanh()\n",
      "    )\n",
      "    (2): Sequential(\n",
      "      (0): Linear(in_features=100, out_features=100, bias=True)\n",
      "      (1): Tanh()\n",
      "    )\n",
      "  )\n",
      "  (dm_linear): Sequential(\n",
      "    (0): Linear(in_features=100, out_features=1, bias=True)\n",
      "    (1): ReLU()\n",
      "  )\n",
      "  (dropout): Dropout(p=0.2, inplace=False)\n",
      "  (out): Linear(in_features=1, out_features=1, bias=True)\n",
      ")\n",
      "Trainable params:  4216504\n"
     ]
    }
   ],
   "source": [
    "model = mz.models.DUET()\n",
    "\n",
    "model.params['task'] = ranking_task\n",
    "model.params['left_length'] = 10\n",
    "model.params['right_length'] = 40\n",
    "model.params['lm_filters'] = 100\n",
    "model.params['mlp_num_layers'] = 2\n",
    "model.params['mlp_num_units'] = 100\n",
    "model.params['mlp_num_fan_out'] = 100\n",
    "model.params['mlp_activation_func'] = 'tanh'\n",
    "\n",
    "model.params['vocab_size'] = preprocessor.context['ngram_vocab_size']\n",
    "model.params['dm_conv_activation_func'] = 'relu'\n",
    "model.params['dm_filters'] = 100\n",
    "model.params['dm_kernel_size'] = 3\n",
    "model.params['dm_right_pool_size'] = 4\n",
    "model.params['dropout_rate'] = 0.2\n",
    "\n",
    "\n",
    "model.build()\n",
    "\n",
    "print(model)\n",
    "print('Trainable params: ', sum(p.numel() for p in model.parameters() if p.requires_grad))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2019-03-20T09:36:06.422264Z",
     "start_time": "2019-03-20T09:36:06.415605Z"
    }
   },
   "outputs": [],
   "source": [
    "optimizer = torch.optim.Adadelta(model.parameters())\n",
    "\n",
    "trainer = mz.trainers.Trainer(\n",
    "    model=model,\n",
    "    optimizer=optimizer,\n",
    "    trainloader=trainloader,\n",
    "    validloader=testloader,\n",
    "    validate_interval=None,\n",
    "    epochs=10\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2019-03-20T09:37:59.341616Z",
     "start_time": "2019-03-20T09:36:06.425086Z"
    },
    "scrolled": false
   },
   "outputs": [
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "55d7405e5fe5449fb0e075414929da9d",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "HBox(children=(IntProgress(value=0, max=102), HTML(value='')))"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[Iter-102 Loss-0.992]:\n",
      "  Validation: normalized_discounted_cumulative_gain@3(0.0): 0.2579 - normalized_discounted_cumulative_gain@5(0.0): 0.3463 - mean_average_precision(0.0): 0.32\n",
      "\n"
     ]
    },
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "02c96ab3f57648aaa4020f1a2a3ccd94",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "HBox(children=(IntProgress(value=0, max=102), HTML(value='')))"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "trainer.run()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "hide_input": false,
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.8"
  },
  "toc": {
   "nav_menu": {},
   "number_sections": true,
   "sideBar": true,
   "skip_h1_title": false,
   "toc_cell": false,
   "toc_position": {},
   "toc_section_display": "block",
   "toc_window_display": false
  },
  "varInspector": {
   "cols": {
    "lenName": 16,
    "lenType": 16,
    "lenVar": 40
   },
   "kernels_config": {
    "python": {
     "delete_cmd_postfix": "",
     "delete_cmd_prefix": "del ",
     "library": "var_list.py",
     "varRefreshCmd": "print(var_dic_list())"
    },
    "r": {
     "delete_cmd_postfix": ") ",
     "delete_cmd_prefix": "rm(",
     "library": "var_list.r",
     "varRefreshCmd": "cat(var_dic_list()) "
    }
   },
   "types_to_exclude": [
    "module",
    "function",
    "builtin_function_or_method",
    "instance",
    "_Feature"
   ],
   "window_display": false
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
